package com.seo.service.business.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seo.function.FunctionT2R;
import com.seo.pojo.ReturnBody;
import com.seo.pojo.transaction.TransactionFlow;
import com.seo.service.business.sdk.BusinessService;
import com.seo.service.transaction.sdk.TransactionService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("businessService")
public class BusinessServiceImpl implements BusinessService {

	@Autowired
	private TransactionService transactionService;

	private Map<String, FunctionT2R<String, Map<String, Object>, ReturnBody>> services = new HashMap<>();

	public void put(String key, FunctionT2R<String, Map<String, Object>, ReturnBody> service) {
		services.put(key, service);

	}

	@Override
	public ReturnBody updatePayBusiness(String tradeId, Map<String, Object> params) {
		String transactionCode = (String) params.get("transactionCode");
		String payMode = (String) params.get("payMode");
		log.info("[{}]-【支付完成-处理账单[{}]】", tradeId, transactionCode);
		ReturnBody rb = ReturnBody.init();
		rb.run(transactionService.updateTransactionFlow(tradeId, transactionCode, payMode,
				TransactionFlow.State.finish.getValue()));

		if (!rb.isSuccess()) {
			return rb.rollback(false, true);
		}

		TransactionFlow tf = rb.get("tf", TransactionFlow.class);
		params.put("tf", tf);
		rb.run(services.get(tf.getType()).invoke(tradeId, params));
		if (!rb.isSuccess()) {
			return rb.rollback(false, true);
		}

		return rb.success();
	}

}
